import { ref, onMounted, onBeforeUnmount, watch, computed, markRaw, nextTick } from "vue";
import { EChartsType, ECElementEvent } from "echarts/core";
import echarts from "./config";
import { debounce } from "@/utils";
export default defineComponent({
    name: 'Echarts',
    props: {
        width: { type: String, required: false },
        height: { type: String, required: false },
        aspectRatio: { type: String, default: "2/1" },
        onClick: { type: Function, required: false },
        theme: { type: String, required: false },
        resize: { type: Boolean, default: true },
        renderer: { type: String, required: false, default: "canvas" },
        option: { type: Object } as any
    },
    setup(props,{expose}) {
        const echartsStyle = computed(() => {
            return props.width || props.height
                ? { height: props.height + "px", width: props.width + "px", aspectRatio: props.aspectRatio }
                : { height: "100%", width: "100%", aspectRatio: props.aspectRatio };
        });

        const chartRef = ref<HTMLDivElement | HTMLCanvasElement>();
        const chartInstance = ref<EChartsType>();

        const draw = () => {
            if (chartInstance.value) {
                chartInstance.value.setOption(props.option, { notMerge: true });
            }
        };

        watch(props, () => {
            draw();
        });

        const init = () => {
            if (!chartRef.value) return;
            chartInstance.value = echarts.getInstanceByDom(chartRef.value);

            if (!chartInstance.value) {
                chartInstance.value = markRaw(
                    echarts.init(chartRef.value, props.theme, {
                        renderer: props.renderer
                    } as any)
                );
                draw();
            }
        };

        const resize = () => {
            if (chartInstance.value && props.resize) {
                chartInstance.value.resize({ animation: { duration: 300 } });
            }
        };

        onMounted(() => {
            nextTick(() => init());
            window.addEventListener("resize", debounce(resize));
        });
        onBeforeUnmount(() => {
            chartInstance.value?.dispose();
            window.removeEventListener("resize", debounce(resize));
        });
        expose({chartInstance})
        return () => (
            <div id="echarts" ref={chartRef} style={echartsStyle.value} />
        );
    }
});
